/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package searchprime;

/**
 *
 * @author TQNINH
 */
public class CountPrimesThread extends Thread {
    private static final int start = 3000000;
    private static int total;
    int count = 0;
    int min, max;
    
    public CountPrimesThread(){
        
    }
    
    public CountPrimesThread(int min, int max){
        this.min = min;
        this.max = max;        
    }
    
    private static boolean isPrime(int x){
        int top = (int)Math.sqrt(x);
        for(int i = 2;i <= top;i++){
            if(x % i == 0){
                return false;
            }
        }
        return true;
    }
    
    private static int countPrimes(int min, int max){
        int count = 0;
        for(int i = min;i <= max;i++){
            if(isPrime(i)){
                count++;
            }
        }
        return count;
    }
    
    synchronized private static void addToTotal(int x){
        total = total + x;
        System.out.println(total + " primes found so far.");
    }
    
    public void run(){
        count = countPrimes(min, max);
        System.out.println("There are " + count + " primes between "
                + min + " and " + max);
        addToTotal(count);
    }
    
    public void countPrimesWithThreads(int numberOfThreads){
        int increment = start / numberOfThreads;
        System.out.println("\nCounting primes between " + (start + 1) + " and "
                + (2 * start) + " using " + numberOfThreads + " threads. " +
                "Please wait...\n");
        
        long startTime = System.currentTimeMillis();
        CountPrimesThread[] worker = new CountPrimesThread[numberOfThreads];
        
        for(int i = 0;i < numberOfThreads;i++){
            worker[i] = new CountPrimesThread(start + i * increment + 1,
                    start + (i + 1) * increment);
        }
        
        total = 0;
        
        for(int i = 0;i < numberOfThreads;i++){
            worker[i].start();
        }
        
        for(int i = 0;i < numberOfThreads;i++){
            while(worker[i].isAlive()){
                try{
                    worker[i].join();
                } catch(InterruptedException e) {
                    
                }
            }
        }
        
        long elapsedTime = System.currentTimeMillis() - startTime;
        System.out.println("\nTotal elapsed time: " + (elapsedTime / 1000.0) +
                "seconds.\n");
    }
}
